package com.android.dx.webanalystjx;

import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.android.dx.webanalystjx.app.App;
import com.android.dx.webanalystjx.mvp.activity.AddBuyerActivity;
import com.android.dx.webanalystjx.mvp.presenter.AddBuyerPresenter;
import com.android.dx.webanalystjx.mvp.view.AddBuyerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.lg.meng.BindPresenter;
import com.lg.meng.utils.AppToast;
import com.lg.meng.utils.FileUtils;
import com.lg.meng.utils.ThreadUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

/**
 * Author: Ligang
 * Date: 2020/01/03
 * Description:
 */
public class JxLoginActivity extends BaseActivity implements AddBuyerView {
    @BindView(R.id.web_container)
    LinearLayout webContainer;

    AgentWeb mAgentWeb;

    @BindPresenter
    AddBuyerPresenter addBuyerPresenter;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_jx_login;
    }

    @Override
    protected void beforeSetContentView() {

    }

    String jxLoginUrl = "https://plogin.m.jd.com/login/login?appid=300";

    @Override
    protected void afterSetContentView() {
        AgentWeb.PreAgentWeb preAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webContainer, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .useDefaultIndicator(-1, 3)
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)
                .interceptUnkownUrl()
                .createAgentWeb()
                .ready();
        mAgentWeb = preAgentWeb.go(jxLoginUrl);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface());
        mAgentWeb.clearWebCache();
        mAgentWeb.getWebCreator().getWebView().loadUrl(jxLoginUrl);
        startTask();

//        ThreadUtils.post(4000,()-> addBuyerPresenter.addBuyer("17711322848", "AAJeD4nvADDpQaCMmhnI751xdpC4QfPaFrtqGGQ1MqTetuI55W2tyPJY8R3sOhFlvbMqGK8qy8Q"));
    }

    private String loginPhone;

    @Override
    public void addBuyerSuccess() {
        AppToast.showLong("添加成功");
        mAgentWeb.clearWebCache();
        mAgentWeb.getWebCreator().getWebView().loadUrl(jxLoginUrl);
        loginPhone = "";
        startTask();
    }

    @Override
    public void addBuyerFailed() {
        AppToast.showLong("添加失败，请手动添加");
        jumpTo(AddBuyerActivity.class, loginPhone);
        finish();
    }

    private class AndroidInterface {
        @JavascriptInterface
        public void showLoginPhone(String phone) {
            loginPhone = phone;
        }
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

    };
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String js = FileUtils.readAssetFile("getphone.js");
            view.loadUrl(js);
            LogUtils.e("zhurujS:\n" + js);
        }
    };

    @Override
    protected void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        super.onDestroy();
    }

    @Override
    protected void exeDestory() {
        super.exeDestory();
        stopTask();
    }

    private Timer timer = new Timer();
    private TimerTask timerTask;

    private void startTask() {
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (!TextUtils.isEmpty(App.getPtkey())) {
                        stopTask();
                        if (RegexUtils.isMobileSimple(loginPhone)) {
                            ThreadUtils.runOnUiThread(() -> addBuyerPresenter.addBuyer(loginPhone, App.getPtkey()));
                            return;
                        }
                        jumpTo(AddBuyerActivity.class, loginPhone);
                        finish();
                    }
                }
            };
            timer.schedule(timerTask, 2000, 500);
        }
    }

    private void stopTask() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    private void log(Object obj) {
        Log.e(TAG, obj + "");
    }

    private static final String TAG = JxLoginActivity.class.getName();
}
